package com.volunteer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.volunteer.common.BusinessException;
import com.volunteer.common.ResultCode;
import com.volunteer.entity.Activity;
import com.volunteer.entity.Evaluation;
import com.volunteer.entity.Registration;
import com.volunteer.entity.User;
import com.volunteer.mapper.ActivityMapper;
import com.volunteer.mapper.EvaluationMapper;
import com.volunteer.mapper.RegistrationMapper;
import com.volunteer.mapper.UserMapper;
import com.volunteer.service.EvaluationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 评价服务实现类
 */
@Service
@RequiredArgsConstructor
public class EvaluationServiceImpl extends ServiceImpl<EvaluationMapper, Evaluation> implements EvaluationService {

    private final ActivityMapper activityMapper;
    private final RegistrationMapper registrationMapper;
    private final UserMapper userMapper;

    /**
     * 创建评价
     *
     * @param evaluation 评价信息
     * @param userId     用户ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createEvaluation(Evaluation evaluation, Long userId) {
        if (evaluation == null || evaluation.getActivityId() == null || userId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 检查活动是否存在
        Activity activity = activityMapper.selectById(evaluation.getActivityId());
        if (activity == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }

        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }

        // 检查是否已评价
        if (isUserEvaluated(evaluation.getActivityId(), userId)) {
            throw new BusinessException(ResultCode.ACTIVITY_ALREADY_EVALUATED);
        }

        // 检查用户是否参加了活动
        LambdaQueryWrapper<Registration> registrationQueryWrapper = new LambdaQueryWrapper<>();
        registrationQueryWrapper.eq(Registration::getActivityId, evaluation.getActivityId())
                .eq(Registration::getUserId, userId)
                .eq(Registration::getStatus, 1) // 已通过审核
                .eq(Registration::getCheckInStatus, 1); // 已签到
        
        if (registrationMapper.selectCount(registrationQueryWrapper) == 0) {
            throw new BusinessException(ResultCode.ACTIVITY_NOT_PARTICIPATED);
        }

        // 设置评价信息
        evaluation.setUserId(userId);
        evaluation.setCreateTime(LocalDateTime.now());
        evaluation.setStatus(0); // 待审核
        
        // 保存评价
        boolean result = this.save(evaluation);

        // 更新报名记录的评价状态
        if (result) {
            Registration registration = registrationMapper.selectOne(registrationQueryWrapper);
            registration.setIsEvaluated(1); // 已评价
            registrationMapper.updateById(registration);
        }

        return result;
    }

    /**
     * 审核评价
     *
     * @param evaluationId 评价ID
     * @param status       状态（1-通过 2-拒绝）
     * @param remark       备注
     * @param operatorId   操作人ID
     * @return 是否成功
     */
    @Override
    public boolean auditEvaluation(Long evaluationId, Integer status, String remark, Long operatorId) {
        if (evaluationId == null || status == null || operatorId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        // 检查评价是否存在
        Evaluation evaluation = this.getById(evaluationId);
        if (evaluation == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }

        // 检查活动是否存在
        Activity activity = activityMapper.selectById(evaluation.getActivityId());
        if (activity == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }

        // 检查操作人权限
        User operator = userMapper.selectById(operatorId);
        if (operator == null || operator.getRole() == 0) { // 不是负责人或管理员
            throw new BusinessException(ResultCode.FORBIDDEN);
        }
        
        if (operator.getRole() == 1 && !activity.getCreatorId().equals(operatorId)) {
            // 如果是负责人，必须是该活动的负责人
            throw new BusinessException(ResultCode.FORBIDDEN);
        }

        // 检查评价状态
        if (evaluation.getStatus() != 0) {
            throw new BusinessException("该评价已被审核");
        }

        // 更新评价状态
        evaluation.setStatus(status);
        evaluation.setAuditTime(LocalDateTime.now());
        evaluation.setAuditRemark(remark);

        return this.updateById(evaluation);
    }

    /**
     * 分页查询活动的评价列表
     *
     * @param page       分页参数
     * @param activityId 活动ID
     * @param status     状态
     * @return 评价列表
     */
    @Override
    public Page<Evaluation> pageActivityEvaluations(Page<Evaluation> page, Long activityId, Integer status) {
        if (activityId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        LambdaQueryWrapper<Evaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Evaluation::getActivityId, activityId);
        
        if (status != null) {
            queryWrapper.eq(Evaluation::getStatus, status);
        }
        
        queryWrapper.orderByDesc(Evaluation::getCreateTime);
        
        return this.page(page, queryWrapper);
    }

    /**
     * 分页查询用户的评价列表
     *
     * @param page   分页参数
     * @param userId 用户ID
     * @param status 状态
     * @return 评价列表
     */
    @Override
    public Page<Evaluation> pageUserEvaluations(Page<Evaluation> page, Long userId, Integer status) {
        if (userId == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR);
        }

        LambdaQueryWrapper<Evaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Evaluation::getUserId, userId);
        
        if (status != null) {
            queryWrapper.eq(Evaluation::getStatus, status);
        }
        
        queryWrapper.orderByDesc(Evaluation::getCreateTime);
        
        return this.page(page, queryWrapper);
    }

    /**
     * 查询用户是否已评价活动
     *
     * @param activityId 活动ID
     * @param userId     用户ID
     * @return 是否已评价
     */
    @Override
    public boolean isUserEvaluated(Long activityId, Long userId) {
        if (activityId == null || userId == null) {
            return false;
        }
        
        LambdaQueryWrapper<Evaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Evaluation::getActivityId, activityId)
                .eq(Evaluation::getUserId, userId);
        
        return this.count(queryWrapper) > 0;
    }

    /**
     * 查询用户的评价
     *
     * @param activityId 活动ID
     * @param userId     用户ID
     * @return 评价信息
     */
    @Override
    public Evaluation getUserEvaluation(Long activityId, Long userId) {
        if (activityId == null || userId == null) {
            return null;
        }
        
        LambdaQueryWrapper<Evaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Evaluation::getActivityId, activityId)
                .eq(Evaluation::getUserId, userId);
        
        return this.getOne(queryWrapper);
    }
} 